//
//  JYTextLabel.m
//  JYDanmu
//
//  Created by jianyong.wang on 2017/12/20.
//  Copyright © 2017年 jianyong.wang. All rights reserved.
//

#import "JYTextLabel.h"
@interface JYTextLabel()
@property (nonatomic, assign) CGRect  superFrame;
@property (nonatomic, assign) CGFloat  danMuHeight;
@property (nonatomic, assign) CGFloat  rollTime;
@end
@implementation JYTextLabel
+ (instancetype)initDML:(NSString *)content originY:(CGFloat)originY superFrame:(CGRect)superFrame danMuHeight:(CGFloat)height rollTime:(CGFloat)rollTime
{
    JYTextLabel * label = [[JYTextLabel alloc]init];
    label.superFrame = superFrame;
    label.danMuHeight = height;
    label.rollTime = rollTime;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor blackColor];
    label.alpha = 0.6;
    label.font = [UIFont systemFontOfSize:14];
    label.text = content;
    [label initDMLWidthWithContent:content orignY:originY];
    return label;
}

/** 计算文本的frame**/
- (void)initDMLWidthWithContent:(NSString *)content orignY:(CGFloat)originY
{
    CGSize size = [self countString:content size:CGSizeMake(MAXFLOAT, self.danMuHeight) font:self.font];
    self.frame = CGRectMake(self.superFrame.size.width, originY, size.width, size.height);
}
/** 动态计算文本size **/
- (CGSize)countString:(NSString *)content size:(CGSize)size font:(UIFont *)font
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    CGSize expectedLabelSize = [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    return CGSizeMake(ceil(expectedLabelSize.width), ceil(expectedLabelSize.height));
}
- (void)beginAnimationChanel:(NSUInteger)chanel complete:(void(^)(bool,NSUInteger))complete
{
    self.startTime = [NSDate date];
    [UIView animateWithDuration:self.rollTime  delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{
        CGRect frame = self.frame;
        frame.origin.x = - self.frame.size.width;
        self.frame = frame;
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeDanmuChanel:chanel complete:complete];
        }
    }];
}
/* 移除弹幕 */
- (void)removeDanmuChanel:(NSUInteger)chanel complete:(void(^)(bool,NSUInteger))complete{
    complete(true,chanel);
    [self stopAnimation];
}
-(void)stopAnimation
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.layer removeAllAnimations];
        [self removeFromSuperview];
    });
}
/**
 计算滚动时间

 @return <#return value description#>
 */
- (CGFloat)dmlSpeed
{
    return (self.frame.size.width + self.superFrame.size.width)/self.danMuHeight;
}
@end
